<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>students</title>
    <link rel="stylesheet" href="/static/css/bootstrap.min.css">
    <link rel="stylesheet" href="/static/css/font-awesome.min.css">
    <style>
        .icon {
            margin: 0 8px;
        }
    </style>

</head>
<body>
<div class="container">
    <div>
        <select id="sel" multiple>
            <option value="1">北京</option>
            <option value="2">上海</option>
            <option value="3">广州</option>
        </select>
        <input type="button" id="btnTest" value="提交">
    </div>
    <div style="padding: 20px 0;">
        <button type="button" class="btn btn-primary" id="addBtn">添加</button>
        <button type="button" class="btn btn-danger">删除</button>
    </div>
    <div>
        <table class="table table-bordered table-hover">
            <thead>
            <tr>
                <th>ID</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
                <th>班级</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody id="tb">
            {% for row in stu_list %}
                 //36行很重要
                <tr nid="{{ row.id }}">
                    <td na="nid">{{ row.id }}</td>
                    <td na="user">{{ row.username }}</td>
                    <td na="age">{{ row.age }}</td>
                    <td na="gender">{{ row.gender }}</td>
                    <td na="cls_id" cid="{{ row.cs_id }}">{{ row.cs.title }}</td>
                    <td>
                        <a class="fa fa-trash icon del-row" aria-hidden="true"></a> |
                        <a class="fa fa-pencil-square-o icon edit-row" aria-hidden="true"></a>
                    </td>
                </tr>
            {% endfor %}
            </tbody>
        </table>
    </div>
</div>

<!-- Modal -->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">创建学生</h4>
            </div>
            <div class="modal-body">
                <form id="fm" class="form-horizontal">{% csrf_token %}
                    <div class="form-group">
                        <label for="user" class="col-sm-2 control-label">User</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="user" placeholder="user">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="pwd" class="col-sm-2 control-label">Password</label>
                        <div class="col-sm-10">
                            <input type="password" class="form-control" name="pwd" placeholder="Password">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="age" class="col-sm-2 control-label">age</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="age" placeholder="age">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="gender" class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-10">
                            <div class="radio">
                                <label class="radio-inline">
                                    <input type="radio" name="gender" value="1"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender" value="0"> 女
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="cls_id" class="col-sm-2 control-label">班级</label>
                        <div class="col-sm-10">
                            <select class="form-control"  name="cls_id">
                                {% for row in class_list %}
                                    <option value="{{ row.id }}">{{ row.title }}</option>
                                {% endfor %}

                            </select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <span id="errMsg" style="color: red;"></span>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="btnSave">保存</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">编辑学生</h4>
            </div>
            <div class="modal-body">
                <form id="edit-fm" class="form-horizontal">{% csrf_token %}
                    <input type="text" name="nid" style="display: none;">
                    <div class="form-group">
                        <label for="user" class="col-sm-2 control-label">User</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="user" placeholder="user">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="pwd" class="col-sm-2 control-label">Password</label>
                        <div class="col-sm-10">
                            <input type="password" class="form-control" name="pwd" placeholder="Password">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="age" class="col-sm-2 control-label">age</label>
                        <div class="col-sm-10">
                            <input type="text" class="form-control" name="age" placeholder="age">
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="gender" class="col-sm-2 control-label">性别</label>
                        <div class="col-sm-10">
                            <div class="radio">
                                <label class="radio-inline">
                                    <input type="radio" name="gender" value="1"> 男
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="gender" value="0"> 女
                                </label>
                            </div>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="cls_id" class="col-sm-2 control-label">班级</label>
                        <div class="col-sm-10">
                            <select class="form-control"  name="cls_id">
                                {% for row in class_list %}
                                    <option value="{{ row.id }}">{{ row.title }}</option>
                                {% endfor %}

                            </select>
                        </div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <span id="errMsg" style="color: red;"></span>
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="btnEditSave">保存</button>
            </div>
        </div>
    </div>
</div>
<div class="modal fade" id="delModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="alert alert-danger" role="alert">
            <h3>删除学生</h3>
            <div><input type="text" id="delNid" style="display: none"></div>
            <div>
                <button type="button" class="btn btn-default" id="cancelDel">取消</button>
                <button type="button" class="btn btn-danger" id="delConfirm">确定</button>
            </div>

        </div>
    </div>
</div>

<script src="/static/js/jquery-3.3.1.js"></script>
<script src="/static/js/bootstrap.js"></script>
<script>
    $(function () {
        bindEvent();
        bindSave();
        bindDelRow();
        bindDelConfirm();
        bindCancelDel();
        bindEdit();
        bindbtnEditConfirm();
        bindTest();
    });

    function bindTest() {
        $('#btnTest').click(function () {
            var values = $('#sel').val();
            console.log(values);
            $.ajax({
                url: '/test/',
                type: 'POST',
                data: {"k": values},
                traditional: true,
                success: function (arg) {
                    console.log(123);

                }
            })

        })

    }
    function bindbtnEditConfirm() {
        var postData = {};
        $("#btnEditSave").click(function () {
            $("#editModal").find('input,select').each(function () {
                var v = $(this).val();
                var n = $(this).attr('name');
                if(n=='gender'){
                    if($(this).prop('checked')){
                        postData[n] = v;
                    }
                }else{
                    postData[n] = v;
                }
            });

            $.ajax({
                url: "/edit_student/",
                type: 'POST',
                data: postData,
                dataType: 'JSON',
                success: function (arg) {
                    if(arg.code == 1000){
                        window.location.reload(); 刷新方式
                        $("#addModal").modal('hide');
                    }else{
                        $('#errMsg').text(dict.msg);
                    }
                }
            })
        });
    }
    /*绑定编辑按钮的事件*/
    function bindEdit() {
        /* 委托*/
        $("#tb").on('click', '.edit-row', function () {
            /*显示模态对话框*/
            $('#editModal').modal('show');
            var valueList =[];
            $(this).parent().prevAll().each(function () {
                var v = $(this).text();
                var n = $(this).attr('na');
                console.log(v,n);
                if(n=='cls_id'){
                    var cid = $(this).attr('cid');
                    $('#editModal select[name="cls_id"]').val(cid);
                }else if(n=='gender'){
                    // v = True
                    if(v=='True'){
                        // radio选择比较特殊 :radio
                        $('#editModal :radio[value="1"]').prop('checked', true);
                    }else{
                        $('#editModal :radio[value="0"]').prop('checked', true);
                    }
                }else{
                    // 这里把隐藏的标签也直接赋值了
                    $("#editModal input[name='" + n + "']").val(v);
                }

            })
        })

    }
    function bindCancelDel() {
        $("#cancelDel").click(function () {
            $("#delModal").modal("hide");
        })

    }

    function bindDelRow() {
        // 此处使用委托，当点击tb时，给.del-row绑定后面的函数。委托一般是找外边的标签，对内部进行委托
        $('#tb').on("click", ".del-row", function () {
            $("#delModal").modal("show");
            var rowId = $(this).parent().parent().attr('nid');
            // 给delNid赋值
            $('#delNid').val(rowId);

        })

    }

    function bindDelConfirm() {
        $('#delConfirm').click(function () {
            var rowId = $('#delNid').val();
            $.ajax({
                url: '/del_student',
                type: "GET",
                data: {"nid": rowId},
                success: function (arg) {
                    var dict = JSON.parse(arg);
                    if(dict.status){
                        $("tr[nid='" + rowId +"']").remove();
                        $("#delModal").modal("hide");
                    }
                }
            })
        })
    }

    function bindEvent() {
        $("#addBtn").click(function () {
            $("#addModal").modal('show');
        })
    }

    function bindSave() {
        var postData = {};
        $("#btnSave").click(function () {
            $("#addModal").find('input,select').each(function () {
                var v = $(this).val();
                var n = $(this).attr('name');
                if(n=='gender'){
                    if($(this).prop('checked')){
                        postData[n] = v;
                    }
                }else{
                    postData[n] = v;
                }
            });

            $.ajax({
                url: "/add_student/",
                type: 'POST',
                data: postData,
                success: function (arg) {
                    // arg是字符串
                    console.log(postData);
                    var dict = JSON.parse(arg);
                    console.log(dict,123);
                    if(dict.status){
                        // 方式一：刷新
                        // window.location.reload(); 刷新方式
                        // 方式二：不刷新
                        createRow(postData, dict.data);
                        $("#addModal").modal('hide');
                    }else{
                        $('#errMsg').text(dict.msg);
                    }
                }
            })
        });
    }
    function createRow(postData, nid) {
        var tr = document.createElement("tr");
        $(tr).attr('nid', nid);
        var tdId = document.createElement("td");
        tdId.innerHTML = nid;
        $(tr).append(tdId);

        var tdUser = document.createElement("td");
        tdUser.innerHTML = postData.user;
        $(tr).append(tdUser);

        var tdAge = document.createElement("td");
        tdAge.innerHTML = postData.age;
        $(tr).append(tdAge);

        var tdGender = document.createElement("td");
        if (postData.gender=='0'){
            tdGender.innerHTML = "False";
        }else{
            tdGender.innerHTML = "True";
        }
        $(tr).append(tdGender);

        var tdClass = document.createElement("td");
        var text = $("select[name='cls_id']").find('option[value="' + postData.cls_id + '"]').text();
        tdClass.innerHTML = text;
        $(tr).append(tdClass);


        var tdHandle = '<td><a class="fa fa-trash icon del-row" aria-hidden="true"></a> | <a class="fa fa-pencil-square-o icon edit-row" aria-hidden="true"></a></td>'
        $(tr).append(tdHandle);
        $("#tb").append(tr);

    }
</script>
</body>
</html>